package com.itheima.reggie.controller;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private IAddressService addressService;

    // 查询地址
    @GetMapping("/list")
    public ResultInfo addressList() {
        // 调用service查询
        List<Address> addresseList = addressService.addressList();
        // 返回结果
        return ResultInfo.success(addresseList);
    }

    // 新增地址
    @PostMapping()
    public ResultInfo save(@RequestBody Address address) { // 1.接收参数
        // 2.调用service保存
        addressService.saveAddress(address);

        // 3.返回成功
        return ResultInfo.success(null);

    }

    // 设置默认地址
    @PutMapping("/default")
    public ResultInfo setDefault(@RequestBody Map<String,Long> param){// 1.接收参数
        Long id = param.get("id");
        // 2.调用service更新
        addressService.setDefault(id);
        // 3.返回成功
        return ResultInfo.success(null);

    }

    // 查询用户的默认收货地址
    @GetMapping("/default")
    public ResultInfo findDefault() {
        //  调用service查询
        Address address = addressService.findDefault();

        return ResultInfo.success(address);
    }


    //回显操作
    @GetMapping("/{id}")
    public ResultInfo findAddressById(@PathVariable Long id){
        Address address = addressService.findAddressById(id);
        return ResultInfo.success(address);
    }

    //编辑操作
    @PutMapping("")
    public ResultInfo updateAddress(@RequestBody Address address){
        addressService.updateAddress(address);
        return ResultInfo.success(null);
    }

    //删除操作
    @DeleteMapping("")
    public ResultInfo deletedAddress(Long ids){
        addressService.deletedAddress(ids);
        return ResultInfo.success(null);
    }
}
